package com.hfut.eeg.service;

import com.hfut.eeg.common.util.BlobListTrans;
import com.hfut.eeg.common.util.EEGUtil;
import com.hfut.eeg.dao.BrainEnergyMapper;
import com.hfut.eeg.dto.BrainEnergy;
import com.hfut.eeg.dto.EEGTrans;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author 梁琦
 * @program: eeg
 * @Package com.hfut.eeg.service
 * @Description: TODO
 * @date 2019-12-11 10:21
 */
@Service
@Scope("singleton")
public class BrainEnergyService {
    private static final Logger LOGGER = LoggerFactory.getLogger(BrainEnergyService.class);
    @Autowired
    private BrainEnergyMapper brainEnergyMapper;

    public int insertBrainEnergy(BrainEnergy trans){
        return brainEnergyMapper.insertBrainEnergy(trans);
    }

    public int updateBrainEnergy(BrainEnergy trans){
        return brainEnergyMapper.updateBrainEnergy(trans);
    }

    public BrainEnergy getBrainEnergy(String eegId){
        return brainEnergyMapper.getBrainEnergy(eegId);
    }


    /**
    * @Description: 通过数组参入脑部能量数据,方法的同步的
    * @param lists 数组数据 eegId 病人ID
    * @return
    * @author 梁琦
    * @date 2019-12-30 20:11
    * @throws
    */
    public synchronized int insertBrainEnergyByArr(ArrayList<ArrayList> lists,String eegId){
        ArrayList<ArrayList> tmp = getBrainEnergy(eegId,0,-1);
        BrainEnergy trans = new BrainEnergy();
        //表述数据库还没有这个数据，需要插入
        if(tmp == null){
            trans = (BrainEnergy) BlobListTrans.transArrToEEG(lists,trans);
            trans.setEegId(eegId);
            LOGGER.info("向BrainEnergy插入数据，病人ID:"+eegId);
            return insertBrainEnergy(trans);
        }
        //更新数据库
        if(lists.size()!=tmp.size()){
            LOGGER.error("插入数据与数据库大小不匹配：");
            return -1;
        }
        for (int i=0;i<tmp.size();i++){
            tmp.get(i).addAll(lists.get(i));
        }
        trans = (BrainEnergy) BlobListTrans.transArrToEEG(tmp,trans);
        trans.setEegId(eegId);
        LOGGER.info("向BrainEnergy更新数据，病人ID:"+eegId);
        return updateBrainEnergy(trans);
    }

    /**
     * @Description: 获取分段脑部通道数据
     * @param eegId 病人ID order 开始数据段位置  num数据段数量
     * @return ArrayList<ArrayList> 脑部通道结果
     * @author 梁琦
     * @date 2019-12-30 20:15
     * @throws
     */
    public ArrayList<ArrayList> getBrainEnergy(String eegId,int start,int num){
        BrainEnergy brainEnergy = brainEnergyMapper.getBrainEnergy(eegId);
        return EEGUtil.getSimpleEEGBySeg(brainEnergy,start,num);
    }
}
